package com.njy.consumer.ribbon;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyRibbonRule implements RibbonRule{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getRequestCount(){
        int current;
        int next;
        for(;;){
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 :current+1;
            if(atomicInteger.compareAndSet(current,next)){
                return next;
            }
        }
    }


    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        int allService = serviceInstances.size();
        int i = getRequestCount() % allService;
        //System.out.println("第"+i+"次请求");
        return serviceInstances.get(i);
    }
}
